const { read, save } = require('../lib/util');

const FILE_NAME = 'data';
const FILE_TAGS = 'tags';

/**
 * 新增数据函数
 * @param {object} newData - 新数据对象
 */
async function addData(newData) {
  try {
    const dataList = await read(FILE_NAME);
    save([...dataList, newData], FILE_NAME);
  } catch (error) {
    throw error;
  }
}

/**
 * 查询数据函数
 * @param {number} pageNo - 页码
 * @param {number} pageSize - 每页数据数量
 * @param {string} name - 名称
 * @param {string[]} tags - 标签数组
 * @param {number} startTime - 开始时间
 * @param {number} endTime - 结束时间
 * @returns {object} - 包含查询结果的对象
 */
/* eslint-disable */
async function getData(pageNo, pageSize, name, tags, startTime, endTime, id) {
  try {
    // 读取data.json文件中的数据
    const dataList = await read(FILE_NAME);
    const tagList = await read(FILE_TAGS);

    let filteredData = dataList.reverse(); //倒叙排列

    if (id) {
      filteredData = filteredData.filter(item => item.id === id);
    }

    // 根据名称进行过滤
    if (name) {
      filteredData = filteredData.filter(item => item.name.includes(name));
    }

    // 根据标签进行过滤
    if (tags) {
      const tagsArray = Array.isArray(tags) ? tags : [tags];
      filteredData = filteredData.filter(item => {
        return tagsArray.every(t => item.tags.includes(t));
      });
    }

    // 根据时间范围过滤
    if (startTime && endTime) {
      if (startTime !== '0' || endTime !== '0') {
        if (startTime !== '0' && endTime == '0') {
          filteredData = filteredData.filter(item => {
            return item.time >= startTime;
          });
        }
        if (startTime == '0' && endTime !== '0') {
          filteredData = filteredData.filter(item => {
            return item.time <= endTime;
          });
        }
        if (startTime !== '0' && endTime !== '0') {
          filteredData = filteredData.filter(item => {
            return item.time >= startTime && item.time <= endTime;
          });
        }
      }
    }

    //将filteredData中tags每个id转为对应的标签名称，存到tagsName中
    filteredData = filteredData.map(item => {
      return {
        ...item,
        tagsInfo: item.tags.map(tagId => {
          const tag = tagList.find(t => t.id === tagId);
          return {
            name: tag ? tag.name : '', // 如果找不到标签，则返回空字符串
            color: tag ? tag.color : '', // 如果找不到标签，则返回空字符串
          };
        }),
      };
    });

    // 计算总数
    const count = filteredData.length;

    if (pageNo && pageSize) {
      // 根据分页信息进行分页
      const startIdx = (pageNo - 1) * pageSize;
      const endIdx = pageNo * pageSize;
      filteredData = filteredData.slice(startIdx, endIdx);
    }
    // 返回查询结果
    return { count, data: filteredData };
  } catch (error) {
    throw error;
  }
}

/**
 * 修改数据函数
 * @param {string} id - 数据ID
 * @param {string} name - 名称
 * @param {string} description - 描述
 * @param {string[]} tags - 标签数组
 * @param {string} url - 图片路径
 */
/* eslint-disable */
async function editData(id, name, description, tags, url) {
  try {
    const dataList = await read(FILE_NAME);
    const isDataExists = dataList.some(data => data.id === id);

    if (!isDataExists) {
      throw { status: 400, message: '数据不存在' };
    }

    const updatedDataList = dataList.map(data => {
      if (data.id === id) {
        data.name = name;
        data.description = description;
        data.tags = tags;
        data.url = url;
      }
      return data;
    });
    save(updatedDataList, FILE_NAME);
  } catch (error) {
    throw error;
  }
}

/**
 * 删除数据函数
 * @param {string} id - 数据ID
 */
async function delData(id) {
  try {
    const dataList = await read(FILE_NAME);

    const isDataExists = dataList.some(data => data.id === id);
    if (!isDataExists) {
      throw { status: 400, message: '数据不存在' };
    }
    const newDataList = dataList.filter(data => data.id !== id);
    save(newDataList, FILE_NAME);
  } catch (error) {
    throw error;
  }
}

// 导出数据查询服务函数
module.exports = {
  getData,
  addData,
  editData,
  delData,
};
